import { ref } from 'vue';

// 定义登录信息的键名
const LOGIN_INFO_KEYS = ['ZY_App_token', 'UNI_LOCALE'];

export function useCacheManagement() {
    // 缓存大小
    const cacheSize = ref(0);

    // 获取本地存储缓存大小
    const getLocalStorageSize = () => {
        let totalSize = 0;
        try {
            const keys = uni.getStorageInfoSync().keys;
            keys.forEach(key => {
                if (!LOGIN_INFO_KEYS.includes(key)) {
                    const value = uni.getStorageSync(key);
                    const dataStr = JSON.stringify(value);
                    totalSize += dataStr.length;
                }
            });
            // 将字节数转换为 KB
            cacheSize.value = (totalSize / 1024).toFixed(2);
        } catch (e) {
            console.error('获取本地存储缓存大小失败:', e);
            cacheSize.value = 0;
        }
    };

    // 获取 APP 端通用缓存大小
    const getAppCacheSize = () => {
        return new Promise((resolve, reject) => {
            document.addEventListener("plusready", () => {
                plus.cache.calculate((size) => {
                    // 将字节数转换为 KB
                    const appCacheSize = (size / 1024).toFixed(2);
                    cacheSize.value = parseFloat(cacheSize.value) + parseFloat(appCacheSize);
                    resolve(appCacheSize);
                }, (e) => {
                    console.error('获取 APP 缓存大小失败:', e);
                    reject(e);
                });
            });
        });
    };

    // 获取总缓存大小
    const getTotalCacheSize = async () => {
        cacheSize.value = 0;
        getLocalStorageSize();
        if (uni.getSystemInfoSync().platform === 'app') {
            try {
                await getAppCacheSize();
            } catch (e) {
                // 处理获取 APP 缓存大小失败的情况
            }
        }
        return cacheSize.value;
    };

    // 清空本地存储缓存（不清除登录信息）
    const clearLocalStorageCache = () => {
        try {
            const keys = uni.getStorageInfoSync().keys;
            keys.forEach(key => {
                if (!LOGIN_INFO_KEYS.includes(key)) {
                    uni.removeStorageSync(key);
                }
            });
        } catch (e) {
            console.error('清空本地存储缓存失败:', e);
        }
    };

    // 清空 APP 端通用缓存
    const clearAppCache = () => {
        return new Promise((resolve, reject) => {
            document.addEventListener("plusready", () => {
                plus.cache.clear(() => {
                    resolve();
                }, (e) => {
                    console.error('清空 APP 缓存失败:', e);
                    reject(e);
                });
            });
        });
    };

    // 清空总缓存
    const clearTotalCache = async () => {
        clearLocalStorageCache();
        if (uni.getSystemInfoSync().platform === 'app') {
            try {
                await clearAppCache();
            } catch (e) {
                // 处理清空 APP 缓存失败的情况
            }
        }
        cacheSize.value = 0;
    };

    return {
        cacheSize,
        getTotalCacheSize,
        clearTotalCache
    };
}

export default useCacheManagement;